const Role = require('../models/roles');
const RoleMenu = require('../models/roles_menus');
const Response = require('../utils/response');
const Menu = require('../models/menus');
const { v4: uuidv4 } = require('uuid');

// 添加 buildMenuTree 函数
function buildMenuTree(menus, parentId = '') {
    return menus
        .filter(menu => menu.parent_id === parentId)
        .map(menu => ({
            ...menu.toObject(),
            meta: {
                title: menu.title,
                icon: menu.icon,
                isShow: !menu.hidden
            },
            children: buildMenuTree(menus, menu.id)
        }))
        .sort((a, b) => (a.sort || 0) - (b.sort || 0));
}

class RoleController {
    // 创建角色
    async createRole(ctx) {
        try {
            const { name, role_desc } = ctx.request.body;

            // 验证角色名称
            // if (!name || !['admin', 'user'].includes(name)) {
            //     ctx.status = 400;
            //     ctx.body = Response.error('无效的角色名称', 400);
            //     return;
            // }

            // 检查角色是否已存在
            const existingRole = await Role.findOne({ name });
            if (existingRole) {
                ctx.status = 400;
                ctx.body = Response.error('角色已存在', 400);
                return;
            }

            // 创建角色
            const role = await Role.create({
                name,
                role_desc: role_desc || `${name}角色`
            });

            ctx.status = 201;
            ctx.body = Response.success(role, '角色创建成功');
        } catch (error) {
            ctx.status = 400;
            ctx.body = Response.error(error.message);
        }
    }

    // 获取所有角色
    async getRoles(ctx) {
        try {
            const { page = 1, limit = 10, name = '' } = ctx.query;
            const skip = (page - 1) * limit;

            // 构建查询条件
            const query = {};
            if (name) {
                query.name = { $regex: name, $options: 'i' };
            }

            // 获取总数
            const total = await Role.countDocuments(query);

            // 获取分页数据
            const roles = await Role.find(query)
                .skip(skip)
                .limit(Number(limit))
                .sort({ createdAt: -1 });

            ctx.body = Response.success({
                total,
                page: Number(page),
                limit: Number(limit),
                data: roles
            });
        } catch (error) {
            ctx.status = 500;
            ctx.body = Response.error(error.message);
        }
    }

    // 获取单个角色
    async getRoleById(ctx) {
        try {
            const role = await Role.findOne({ id: ctx.params.id });
            if (!role) {
                ctx.status = 404;
                ctx.body = Response.error('角色不存在', 404);
                return;
            }
            // 获取角色的菜单权限
            const roleMenus = await RoleMenu.find({ role_id: role.id });
            const roleData = role.toObject();
            roleData.menus = await Menu.find({ id: { $in: roleMenus.map(rm => rm.menu_id) } });
            
            ctx.body = Response.success(roleData);
        } catch (error) {
            ctx.status = 500;
            ctx.body = Response.error(error.message);
        }
    }

    // 更新角色
    async updateRole(ctx) {
        try {
            const role = await Role.findOneAndUpdate(
                { id: ctx.params.id },
                ctx.request.body,
                { new: true, runValidators: true }
            );
            if (!role) {
                ctx.status = 404;
                ctx.body = Response.error('角色��存在', 404);
                return;
            }
            ctx.body = Response.success(role);
        } catch (error) {
            ctx.status = 400;
            ctx.body = Response.error(error.message);
        }
    }

    // 删除角色
    async deleteRole(ctx) {
        try {
            const role = await Role.findOneAndDelete({ id: ctx.params.id });
            if (!role) {
                ctx.status = 404;
                ctx.body = Response.error('角色不存在', 404);
                return;
            }
            // 删除角色菜单关联
            await RoleMenu.deleteMany({ role_id: role.id });
            ctx.body = Response.success(null, '删除成功');
        } catch (error) {
            ctx.status = 500;
            ctx.body = Response.error(error.message);
        }
    }

    // 设置角色菜单
    async setRoleMenus(ctx) {
        try {
            const { menuIds = [] } = ctx.request.body;
            const roleId = ctx.params.id;
            
            console.log('请求参数:', { roleId, menuIds });

            // 验证参数
            if (!Array.isArray(menuIds)) {
                ctx.status = 400;
                ctx.body = Response.error('菜单ID列表格式错误', 400);
                return;
            }

            // 查找角色
            const role = await Role.findOne({ id: roleId });
            if (!role) {
                ctx.status = 404;
                ctx.body = Response.error('角色不存在', 404);
                return;
            }

            // 验证所有菜单是否存在
            if (menuIds.length > 0) {
                const menus = await Menu.find({ id: { $in: menuIds } });
                if (menus.length !== menuIds.length) {
                    ctx.status = 400;
                    ctx.body = Response.error('存在无效的菜单ID', 400);
                    return;
                }
            }

            // 删除原有的菜单关联
            await RoleMenu.deleteMany({ role_id: role.id });

            // 创建新的菜单关联
            if (menuIds.length > 0) {
                const roleMenus = menuIds.map(menuId => ({
                    id: uuidv4(),
                    role_id: role.id,
                    menu_id: menuId
                }));

                await RoleMenu.insertMany(roleMenus);
            }

            // 返回更新后的角色菜单列表
            const updatedRoleMenus = await RoleMenu.find({ role_id: role.id });
            const menuDetails = await Menu.find({ id: { $in: updatedRoleMenus.map(rm => rm.menu_id) } });
            
            ctx.body = Response.success({
                role: role,
                menus: menuDetails
            }, '角色菜单设置成功');

        } catch (error) {
            console.error('设置角色菜单失败:', error);
            ctx.status = 500;
            ctx.body = Response.error(error.message);
        }
    }

    // 获取角色的菜单树
    async getRoleMenuTree(ctx) {
        try {
            const roleId = ctx.params.id;

            // 查找角色
            const role = await Role.findOne({ id: roleId });
            if (!role) {
                ctx.status = 404;
                ctx.body = Response.error('角色不存在', 404);
                return;
            }

            // 获取角色的菜单权限
            const roleMenus = await RoleMenu.find({ role_id: role.id });
            const menuIds = roleMenus.map(rm => rm.menu_id);

            // 获取所有菜单
            const allMenus = await Menu.find().sort({ sort: 1 });

            // 过滤出该角色拥有的菜单
            const roleMenuList = allMenus.filter(menu => menuIds.includes(menu.id));

            // 构建菜单树
            const menuTree = buildMenuTree(roleMenuList);

            ctx.body = Response.success({
                role: {
                    id: role.id,
                    name: role.name,
                    role_desc: role.role_desc
                },
                menus: menuTree
            });

        } catch (error) {
            console.error('获取角色菜单树失败:', error);
            ctx.status = 500;
            ctx.body = Response.error(error.message);
        }
    }
}

module.exports = new RoleController(); 